﻿using Microsoft.Extensions.DependencyInjection;
using PLM.ConfigurationCenter.Core;
using PLM.ConfigurationCenter.CustomForm;
using PLM.ConfigurationCenter.EventBus.RabbitMQ;
using PLM.ConfigurationCenter.Handler;
using PLM.ConfigurationCenter.Model;
using PLM.ConfigurationCenter.Service;
using PLM.ConfigurationCenter.SqlSugar;
using RabbitMQ.Client;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace PLM.ConfigurationCenter {
    internal static class Program {
        private static Mutex mutex;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main() {
            const string appName = "SingleInstanceWinFormsApp";
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            mutex = new Mutex(true, appName);
            if (mutex.WaitOne(0, false)) {
                //创建服务容器
                var services = new ServiceCollection();
                //添加服务注册
                ConfigureServices(services);

                //先用DI容器生成 serviceProvider, 然后通过 serviceProvider 获取Main Form的注册实例
                var serviceProvider = services.BuildServiceProvider();
                AppHelper.Initialization(serviceProvider);
                MainForm mainform = serviceProvider.GetService<MainForm>();

                bool check = CommonServerHelper.CheckPgDatabaseHealth(out _);
                if (!check) {
                    MessageBoxButtons mess = MessageBoxButtons.OKCancel;
                    DialogResult d = MessageBox.Show("缺少配置或者连接不正确,是否要进行配置检查？", "提示", mess);
                    if (d == DialogResult.OK) {
                        StartForm form = serviceProvider.GetService<StartForm>();
                        form.StartPosition = FormStartPosition.CenterScreen;
                        if (form.ShowDialog() == DialogResult.OK) {
                            Application.Run(mainform);
                        }
                    }
                } else {
                    Application.Run(mainform);
                }
            } else {
                Process currentProcess = Process.GetCurrentProcess();
                Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);

                foreach (Process process in processes) {
                    if (process.Id != currentProcess.Id && process.MainModule.FileName == currentProcess.MainModule.FileName) {
                        NativeMethods.SetForegroundWindow(process.MainWindowHandle);
                        break;
                    }
                }
            }
        }
        static class NativeMethods {
            [System.Runtime.InteropServices.DllImport("user32.dll")]
            public static extern bool SetForegroundWindow(IntPtr hWnd);
        }

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="services"></param>
        public static void ConfigureServices(IServiceCollection services) {
            //批量注入可以使用Scrutor或者自己封装
            services.AddScoped(typeof(StartForm));//
            services.AddScoped(typeof(DbSyncForm));
            services.AddScoped(typeof(MainForm));

            services.AddSingleton<IRabbitMQConnection>(sp => {

                var factory = new ConnectionFactory() {
                    HostName = "192.168.5.168",
                    DispatchConsumersAsync = true
                };
                factory.UserName = "admin";
                factory.Password = "123";
                //if (!string.IsNullOrEmpty(Appsettings.app(new string[] { "RabbitMQ", "UserName" }))) {
                //    factory.UserName = Appsettings.app(new string[] { "RabbitMQ", "UserName" });
                //}

                //if (!string.IsNullOrEmpty(Appsettings.app(new string[] { "RabbitMQ", "Password" }))) {
                //    factory.Password = Appsettings.app(new string[] { "RabbitMQ", "Password" });
                //}

                var retryCount = 5;
                //if (!string.IsNullOrEmpty(Appsettings.app(new string[] { "RabbitMQ", "RetryCount" }))) {
                //    retryCount = int.Parse(Appsettings.app(new string[] { "RabbitMQ", "RetryCount" }));
                //}

                return new RabbitMQConnection(factory, retryCount);
            });
            var dbModel = DbManager.DbContext.Queryable<DatabaseInfoModel>().First(p => p.Id == "AuxiliaryDb");
            var dbconn = CommonServerHelper.GetDBConn(dbModel);
            services.AddScoped<ISqlSugarClient>(sp => {
                var client = new SqlSugarClient(new ConnectionConfig() {
                    DbType = DbType.PostgreSQL,
                    InitKeyType = InitKeyType.Attribute,
                    IsAutoCloseConnection = true,
                    ConnectionString = dbconn,
                    ConfigureExternalServices = new ConfigureExternalServices {
                        EntityService = (c, p) => {
                            if (p.IsPrimarykey == false && new NullabilityInfoContext().Create(c).WriteState is NullabilityState.Nullable) {
                                p.IsNullable = true;
                            }
                        }
                    }
                });
                return client;
            });
            services.AddTransient<LogInfoService>();
        }

    }
}
